package cn.nit.blog.controller;

import cn.nit.blog.dto.CommentDto;
import cn.nit.blog.dto.IndexDataDto;
import cn.nit.blog.entity.Post;
import cn.nit.blog.entity.User;
import cn.nit.blog.exception.BlogException;
import cn.nit.blog.service.IPostService;
import cn.nit.blog.service.impl.LikeService;
import cn.nit.blog.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wjx
 * @since 2023-03-24
 */
@Controller
@RequestMapping("/post")
public class PostController {

    @Autowired
    private IPostService postService;

    @Autowired
    private LikeService likeService;

    @PostMapping("/create")
    @ResponseBody
    public Result create(HttpSession session, @RequestBody Post post){

//        根据用户id判断用户是否登陆了
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null) {
            throw new BlogException(1001,"登录已过期，请先登录！");
        }

//        从前端获取userID，title，content后，设置其他属性的值
        post.setCreateTime(new Date());
        post.setScore(0.343);
        post.setStatus(0);
        post.setType(0);
        post.setUserId(loginUser.getId());
        post.setCommentCount(0);

        System.out.println(post);

//        放入数据库中
        postService.save(post);

//        重定向到首页
        return Result.ok();
    }

    @RequestMapping("/detail/{id}")
    public String detail(@PathVariable Integer id, Model model, HttpSession session){
//        从前端拿到帖子id

//        根据帖子id向数据库里查询帖子详情信息（包括发帖人头像，发帖人，发帖时间，帖子标题，帖子内容，点赞，评论数）
        IndexDataDto indexDataDto = postService.findPostDetail(id);
        System.out.println(indexDataDto);

//        根据id查询到下面的评论
        // 根据帖子ID查询它下面的评论
        List<CommentDto> commentDtoList = postService.getCommentListByPostId(id);

        // 3.查询帖子点赞数量以及当前用户是否点赞
        Long likeCount = likeService.likeSize(id, 1);

        User loginUser = (User) session.getAttribute("loginUser");
        boolean like = false; // 默认没有点赞
        if (loginUser != null) {
            // 只有用户登录了才能判断出用户是否点赞
            like = likeService.isLike(id, 1, loginUser.getId());
        }

//        把数据放进model，转发到discuss-detail页面
        model.addAttribute("indexDataDto",indexDataDto);
        model.addAttribute("commentDtoList",commentDtoList);
        model.addAttribute("likeStatus", like ? 1 : 0);
        model.addAttribute("likeCount", likeCount);

        return "site/discuss-detail";
    }

}
